package serviceTest;

import org.springframework.beans.factory.annotation.Autowired;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import win.ganbo.ssm.dao.UserMapper;
import win.ganbo.ssm.entity.User;
import win.ganbo.ssm.enums.Activate;
import win.ganbo.ssm.enums.Type;

import java.util.Date;

/**
 *
 * @author ganbo E-mail:bo.gan@56qq.com
 * @since 2017-11-12 17:24
 */

public class MyWebmagic extends BaseTest implements PageProcessor {

    @Autowired
    private UserMapper userMapper;


    private Site site = Site.me().setRetryTimes(3).setSleepTime(5000);

    public void process(Page page) {
        // 部分二：定义如何抽取页面信息，并保存下来
        page.putField("author", page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString());
        page.putField("name", page.getHtml().xpath("//h1[@class='entry-title public']/strong/a/text()").toString());
        if (page.getResultItems().get("name") == null) {
            //skip this page
            page.setSkip(true);
        }
        page.putField("readme", page.getHtml().xpath("//div[@id='readme']/tidyText()"));

        // 部分三：从页面发现后续的url地址来抓取 .all() 获取当前页面匹配后续链接正则表达式的素有url
        page.addTargetRequests(page.getHtml().links().regex("(https://github\\.com/[\\w\\-]+/[\\w\\-]+)").all());
        System.out.println("name======================>" + page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString());

        String name = page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString();
        User user = new User();
        user.setUsername(name);
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("四川省成都市：" + System.currentTimeMillis());
        user.setUsertype(Type.ADMIN);
        user.setActivate(Activate.YES);
        userMapper.insert(user);
    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new MyWebmagic())
                //从"https://github.com/code4craft"开始抓
                .addUrl("https://github.com/code4craft")
                .addPipeline(new JsonFilePipeline("D:\\webmagic\\"))
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .run();
    }
}
